<?php

class LoginController extends Zend_Controller_Action
{

    public function init()
    {
        session_start("login");
    }

    private function linkedinLogin()
    {
        define('API_KEY',      '77rwtz7m2sa8ea');
        define('API_SECRET',   '9S7JcdCi2tlrAnnm');
        define('REDIRECT_URI', 'http://jobsel.com.br/login/index/mode/linkedin/');
        define('SCOPE',        'r_fullprofile r_emailaddress');
        
        // You'll probably use a database
        session_name('linkedin');
        session_start();
 
        // OAuth 2 Control Flow
        if (isset($_GET['error'])) {
            // LinkedIn returned an error
            print $_GET['error'] . ': ' . $_GET['error_description'];
            exit;
        } elseif (isset($_GET['code'])) {
            $params = array('grant_type' => 'authorization_code',
                            'client_id' => API_KEY,
                            'client_secret' => API_SECRET,
                            'code' => $_GET['code'],
                            'redirect_uri' => REDIRECT_URI,
                      );
            
            // Access Token request
            $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

            // Tell streams to make a POST request
            $context = stream_context_create(
                            array('http' => 
                                array('method' => 'POST',
                                )
                            )
                        );

            // Retrieve access token information
            $response = file_get_contents($url, false, $context);

            // Native PHP object, please
            $token = json_decode($response);
            
            // Store access token and expiration time
            $_SESSION['access_token'] = $token->access_token; // guard this! 
            $_SESSION['expires_in']   = $token->expires_in; // relative time (in seconds)
            $_SESSION['expires_at']   = time() + $_SESSION['expires_in']; // absolute time
        } else { 
            if ((empty($_SESSION['expires_at'])) || (time() > $_SESSION['expires_at'])) {
                // Token has expired, clear the state
                $_SESSION = array();
            }
            if (empty($_SESSION['access_token'])) {
                // Start authorization process
                $params = array('response_type' => 'code',
                            'client_id' => API_KEY,
                            'scope' => SCOPE,
                            'state' => uniqid('', true), // unique long string
                            'redirect_uri' => REDIRECT_URI,
                      );

                // Authentication request
                $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

                // Needed to identify request when it returns to us
                $_SESSION['state'] = $params['state'];

                // Redirect user to authenticate
                header("Location: $url");
                exit;
            }
        }
        
        // Congratulations! You have a valid token. Now fetch your profile 
        $params = array('oauth2_access_token' => $_SESSION['access_token'],
                        'format' => 'json',
                  );
        // Need to use HTTPS
        $url = 'https://api.linkedin.com' . '/v1/people/~:(id,first-name,last-name,email-address,public-profile-url)' . '?' . http_build_query($params);
        // Tell streams to make a (GET, POST, PUT, or DELETE) request
        $context = stream_context_create(
                        array('http' => 
                            array('method' => 'GET',
                            )
                        )
                    );
        // Hocus Pocus
        $response = file_get_contents($url, false, $context);
        // Native PHP object, please
        $user = json_decode($response);
        // Efetuar Login
        $dbTable = new Application_Model_DbTable_User();
        $resultSet = $dbTable->fetchRow(array('kind = ?' => 'linkedin','verification_code = ?' => $user->id));
        if (isset($resultSet->email)) {
          $dbUser = array(
            'name' => $resultSet->name,
            'email' => $resultSet->email,
            'url' => $resultSet->url,
            'admin' => $resultSet->admin,
            'active' => $resultSet->active,
            'kind' => $resultSet->kind,
            'verification_code' => $resultSet->verification_code
          );
          return $dbUser;
        } else {
          $newUser = array(
              'name' => $user->firstName.' '.$user->lastName,
              'email' => $user->emailAddress,
              'url' => $user->publicProfileUrl,
              'admin' => false,
              'active' => true,
              'kind' => 'linkedin',
              'verification_code' => $user->id
          );
          $resultset = $dbTable->insert($newUser);
          return $newUser;
        }
    }

    private function facebookLogin()
    {
        $appId = '1525142274376925';
        $appSecret = '8d12b0225e8ecb2256340b9c6ecfd0c8';
        $redirectUri = urlencode('http://jobsel.com.br/login/index/mode/facebook/');
        $code = $_GET['code'];
        
        // Monta a url para obter o token de acesso
        $token_url = "https://graph.facebook.com/oauth/access_token?"
        . "client_id=" . $appId . "&redirect_uri=" . $redirectUri
        . "&client_secret=" . $appSecret . "&code=" . $code;

        // Requisita token de acesso
        $response = @file_get_contents($token_url);
        if($response){
            $params = null;
            parse_str($response, $params);
            // Se veio o token de acesso
            if(isset($params['access_token']) && $params['access_token']){
              $graph_url = "https://graph.facebook.com/me?access_token=" 
              . $params['access_token'];
              // Obtém dados através do token de acesso
              //var_dump(file_get_contents($graph_url));break;
              $user = json_decode(file_get_contents($graph_url));
              //Verificar usuário
              $dbTable = new Application_Model_DbTable_User();
              $resultSet = $dbTable->fetchRow(array('kind = ?' => 'facebook','verification_code = ?' => $user->id));
              if (isset($resultSet->email)) {
                $dbUser = array(
                  'name' => $resultSet->name,
                  'email' => $resultSet->email,
                  'url' => $resultSet->url,
                  'admin' => $resultSet->admin,
                  'active' => $resultSet->active,
                  'kind' => $resultSet->kind,
                  'verification_code' => $resultSet->verification_code
                );
                return $dbUser;
              } else {
                $newUser = array(
                    'name' => $user->name,
                    'email' => $user->email,
                    'url' => $user->link,
                    'admin' => false,
                    'active' => true,
                    'kind' => 'facebook',
                    'verification_code' => $user->id
                );
                $resultset = $dbTable->insert($newUser);
                return $newUser;
              }
            } else {
              return 'error';
            }
        } else {
            return 'error';
        }
    }

    private function googleLogin()
    {
        //$client->setClientId('1059099119799-2hi4tjb47251fv6kb70ei15d06op4liq.apps.googleusercontent.com');
        //$client->setClientSecret('EdlCjKuKYlEePzXHEUSEkCOJ');
        //$client->setRedirectUri(urlencode('http://jobsel.com.br/Jobsel/public/login/'));
    }

    public function indexAction()
    {
        $parametros = $this->getAllParams();
        switch ($parametros['mode']) {
          case 'facebook':
              $user = $this->facebookLogin();
              break;
          case 'linkedin':
              $user = $this->linkedinLogin();
              break;
          case 'google':
              $user = $this->googleLogin();
              break;
        }
        /* Validates User */
        if (isset($user)) {
            $dbUser = new Application_Model_DbTable_User();
            $getUser = $dbUser->fetchAll(
                    $dbUser->select('id, name, email, admin, kind')
                           ->where('active = ?', '1')
                           ->where('kind = ?', $user['kind'])
                           ->where('verification_code = ?', $user['verification_code'])
            );
            if (count($getUser) == 1) {
                $_SESSION["login_id"] = $getUser[0]['id'];
                $_SESSION["login_name"] = $getUser[0]['name'];
                $_SESSION["login_email"] = $getUser[0]['email'];
                $_SESSION["login_admin"] = $getUser[0]['admin'];
                $_SESSION["login_kind"] = $getUser[0]['kind'];
                
                if (isset($_SESSION["redirect_to"]) && ($_SESSION["redirect_to"] != NULL)) {
                    if ($_SESSION["redirect_to"] == 'empresa') {
                        $_SESSION["message_success"] = "Login efetuado com sucesso.";
                        $_SESSION["redirect_to"] = NULL;
                        $this->_helper->redirector('nova-empresa','evaluation');
                    } else {
                        $_SESSION["message_success"] = "Login efetuado com sucesso.";
                        $empresa = $_SESSION["redirect_to"];
                        $_SESSION["redirect_to"] = NULL;
                        $this->_helper->redirector('avaliar','evaluation','', array('company' => $empresa));
                    }
                } else {
                    $this->_helper->redirector('painel','login');
                }
            }else{
              $_SESSION["message_danger"] = "Ocorreu uma falha ao logar.Tente novamente.";
              $this->_helper->redirector('index','login');
            }
        }
    }

    public function painelAction()
    {
        if (!isset($_SESSION["login_id"])) {
            $this->_helper->redirector('index','login');
        } else {
            /* Inicia Instancias de banco */
            $dbCompany = new Application_Model_DbTable_Company();
            $dbEvaluation = new Application_Model_DbTable_Evaluation();
            $getEvaluations = $dbEvaluation->fetchAll(
                    $dbEvaluation->select('id, company_id, created_at, active')
                                 ->where('user_id = ?', $_SESSION["login_id"])
            );
            $companies = array();
            $countInatives = 0;
            $countAtives = 0;
            foreach ($getEvaluations AS $eval) {
                $evaluation['id'] = $eval['id'];
                $evaluation['date'] = $eval['created_at'];
                $evaluation['active'] = $eval['active'];
                if ($eval['active'] == 1) {
                    $countAtives = $countAtives + 1;
                } else {
                    $countInatives = $countInatives + 1;
                }
                $getCompanyName = $dbCompany->fetchAll(
                    $dbCompany->select('name, friendly_name')
                              ->where('id = ?', $eval["company_id"])
                );
                $evaluation['company_name'] = $getCompanyName[0]['name'];
                $evaluation['company_friendly_name'] = $getCompanyName[0]['friendly_name'];
                $companies[] = $evaluation;
            }
            $this->view->numEvalAtive = $countAtives;
            $this->view->numEvalInative = $countInatives;
            $this->view->companies = $companies;
        }
    }

    public function logoutAction()
    {
        session_destroy();
        $_SESSION["message_success"] = "Deslogado com sucesso.";
        $this->_helper->redirector('index','evaluation');
    }


}



